package com.plm.maque.mongo.impl;

import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.plm.maque.entity.MongoImage;
import com.plm.maque.mongo.ImageOperate;
import com.plm.maque.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;

/**
 * @author Limi
 * @create 2019-04-21 17:04
 */
@Slf4j
@Component
public class ImageOperateImpl implements ImageOperate {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Override
    public String saveImageToMongoDB(MongoImage mongoImage) {
        ObjectId id = gridFsTemplate.store(mongoImage.getInputStream(), MongoImage.class.getSimpleName(), mongoImage.getContentType());
        if (StringUtils.isNull(id))
            log.error("保存到mongodb出错");
        return id.toString();
    }

    /**
     * 根据objectId从mongodb上获取文件信息流
     * @param objectId
     * @return
     */
    @Override
    public MongoImage getImageFromMongoDB(String objectId) {
        if (StringUtils.isNull(objectId))
            return null;
        try {
            Query query = new Query( Criteria.where("_id").is(objectId));
            GridFSFile gfsFile = gridFsTemplate.findOne(query);

            if (null == gfsFile)
                return null;

            GridFsResource gridFsResource = new GridFsResource(gfsFile,
                    GridFSBuckets.create(mongoTemplate.getDb()).openDownloadStream(gfsFile.getObjectId()));

            MongoImage mongoImage = new MongoImage();
            mongoImage.setDataId(objectId)
                    .setInputStream(gridFsResource.getInputStream())
                    .setContentType(gridFsResource.getContentType())
                    .setFileName(gridFsResource.getFilename())
                    .setChunkSize(gfsFile.getChunkSize());

            return mongoImage;
        } catch (Exception e) {
            log.error("获取图片异常：{}", e.getMessage());
        }

        return null;
    }
}
